package com.tanhua.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.commons.utils.Constants;
import com.itheima.commons.utils.JwtUtils;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private MovementApi movementApi;

    public Map login(Map map) {
        //1、获取请求参数
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");

        String key = Constants.CAP_CODE + uuid;
        String code = redisTemplate.opsForValue().get(key);
        //校验验证码
        if (code == null || !code.equals(verificationCode)) {
            throw new BusinessException("验证码错误");
        }
        //查询用户是否存在及校验密码
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(username != null, Admin::getUsername, username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        String s = new String(DigestUtils.md5Hex(password));
        if (admin == null || !admin.getPassword().equals(DigestUtils.md5Hex(password))) {
            throw new BusinessException("用户名或密码错误");
        }

        //封装token信息
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", admin.getId());
        hashMap.put("username", admin.getUsername());
        //生成token
        String token = JwtUtils.getToken(hashMap);

        //6、构造返回值
        HashMap<String, String> retMap = new HashMap<>();
        retMap.put("token", token);

        return retMap;
    }

    public AdminVo profile() {
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        return AdminVo.init(admin);
    }

}
